package com.service.impl;

import com.dto.UserDTO;
import com.mapper.UsersMapper;
import com.pojo.Result;
import com.pojo.Users;
import com.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {

    private final UsersMapper usersMapper;

    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;


    @Autowired
    public UserServiceImpl(UsersMapper usersMapper) {
        this.usersMapper = usersMapper;
    }

    @Override
    @Transactional
    public Result<Users> register(Users user) {
        // 检查用户名是否已存在
        if (usersMapper.checkUsernameExists(user.getUsername()) > 0) {
            return Result.error("用户名已存在");
        }

        // 检查邮箱是否已存在
        if (usersMapper.checkEmailExists(user.getEmail()) > 0) {
            return Result.error("邮箱已被注册");
        }

        // 密码加密
        String hashedPassword = BCrypt.hashpw(user.getPassword(), BCrypt.gensalt());
        user.setPassword(hashedPassword);

        // 插入用户
        int result = usersMapper.insertUser(user);
        if (result > 0) {
            // 不返回密码
            user.setPassword(null);
            return Result.success(user);
        } else {
            return Result.error("注册失败");
        }
    }

    @Override
    public Result<Users> login(String username, String password) {
        Users user = usersMapper.selectUserByUsername(username);
        if (user == null) {
            return Result.error("用户不存在");
        }

        // 验证密码
        if (BCrypt.checkpw(password, user.getPassword())) {
            // 不返回密码
            user.setPassword(null);
            return Result.success(user);
        } else {
            return Result.error("密码错误");
        }
    }

    @Override
    public Result<Users> getUserById(Long id) {
        Users user = usersMapper.selectUserById(id);
        if (user != null) {
            // 不返回密码
            user.setPassword(null);
            return Result.success(user);
        } else {
            return Result.error("用户不存在");
        }
    }

        @Override
        @Transactional
        public Result<Void> updateUser(Users user) {
            // 检查用户名是否被占用（排除自己）
            if (usersMapper.checkUsernameExists(user.getUsername()) > 0) {
                Users existingUser = usersMapper.selectUserByUsername(user.getUsername());
                if (!existingUser.getId().equals(user.getId())) {
                    return Result.error("用户名已被占用");
                }
            }

        // 检查邮箱是否被占用（排除自己）
        if (usersMapper.checkEmailExists(user.getEmail()) > 0) {
            Users existingUser = usersMapper.selectUserByEmail(user.getEmail());
            if (!existingUser.getId().equals(user.getId())) {
                return Result.error("邮箱已被占用");
            }
        }

        int result = usersMapper.updateUser(user);
        if (result > 0) {
            return Result.success();
        } else {
            return Result.error("更新失败");
        }
    }

    @Override
    @Transactional
    public Result<Void> updateAvatar(Long id, String avatarUrl) {
        int result = usersMapper.updateAvatar(id, avatarUrl);
        if (result > 0) {
            return Result.success();
        } else {
            return Result.error("更新头像失败");
        }
    }

    @Override
    @Transactional
    public Result<Void> updatePassword(Long id, String oldPassword, String newPassword) {
        Users user = usersMapper.selectUserById(id);
        if (user == null) {
            return Result.error("用户不存在");
        }

        // 验证原密码
        if (!BCrypt.checkpw(oldPassword, user.getPassword())) {
            return Result.error("原密码错误");
        }

        // 加密新密码
        String hashedPassword = BCrypt.hashpw(newPassword, BCrypt.gensalt());
        int result = usersMapper.updatePassword(id, hashedPassword);
        if (result > 0) {
            return Result.success();
        } else {
            return Result.error("密码更新失败");
        }
    }

    @Override
    @Transactional
    public Result<Void> updateBio(Long id, String bio) {
        int result = usersMapper.updateBio(id, bio);
        if (result > 0) {
            return Result.success();
        } else {
            return Result.error("更新个人简介失败");
        }
    }

    @Override
    @Transactional
    public Result<Void> deleteUser(Long id) {
        int result = usersMapper.deleteUser(id);
        if (result > 0) {
            return Result.success();
        } else {
            return Result.error("删除用户失败");
        }
    }

    @Override
    public Result<List<Users>> getAllUsers(int page, int size) {
        int offset = (page - 1) * size;
        List<Users> users = usersMapper.selectUsersByPage(offset, size);

        // 不返回密码
        users.forEach(u -> u.setPassword(null));

        return Result.success(users);
    }

    @Override
    public Result<Boolean> checkUsernameAvailable(String username) {
        int count = usersMapper.checkUsernameExists(username);
        return Result.success(count == 0);
    }

    @Override
    public Result<Boolean> checkEmailAvailable(String email) {
        int count = usersMapper.checkEmailExists(email);
        return Result.success(count == 0);
    }



    @Override
    public Result<UserDTO> getUserDTOById(Long id) {
        try {
            if (id == null || id <= 0) {
                return Result.error("无效的用户ID");
            }

            UserDTO userDTO = usersMapper.selectUserDTOById(id);

            if (userDTO == null) {
                return Result.error("用户不存在");
            }

            return Result.success(userDTO);
        } catch (Exception e) {
            return Result.error(500, "获取用户信息失败: " + e.getMessage());
        }
    }

    @Override
    public Users getByEmail(String email) {
        return usersMapper.selectUserByEmail(email);
    }
    @Override
    public void sendCode(String email) {
        System.out.println("开始发送验证码到: " + email);
        SimpleMailMessage msg = new SimpleMailMessage();
        msg.setFrom("1547417010@qq.com");
        msg.setSubject("青书推广 - 验证码");
        String code = String.format("%06d", (int)(Math.random() * 900000 + 100000));
        msg.setText("您的验证码是: " + code + "，有效期为5分钟。");
        msg.setTo(email);
        try {
            mailSender.send(msg);
            System.out.println("验证码发送成功，邮箱: " + email);
            System.out.println("验证码: " + code);

            redisTemplate.opsForValue().set("code:" + email, code, 5, TimeUnit.MINUTES);
        } catch (Exception e) {
            System.err.println("验证码发送失败！邮箱: " + email);
            System.err.println("失败原因: " + e.getMessage());
            e.printStackTrace();
        }
    }

}